#include "BigCute.h"

// 用于发送数据到串口

static void Send(uint8_t* data, uint16_t length) {
    HAL_UART_Transmit(&GetUartHandle(USART1_INDEX)->huart, data, length, HAL_MAX_DELAY);
}

static void SendOverDMA(uint8_t* data, uint16_t length) {
    HAL_UART_Transmit_DMA(&GetUartHandle(USART1_INDEX)->huart, data, length);
}

// 串口调试函数，灰度图像数据上传BigCute
void SendImageStart(uint16_t width, uint16_t height) {
    // 帧头发送
    image_header_t header;
    header.sof = 0x28;
    header.type = 0x22;
    header.width = width;
    header.height = height;
    header.header_check = 0x2D;
    Send((uint8_t*)&header, sizeof(image_header_t) - 1);
}

void SendImageData(const uint8_t* data, uint16_t length) {
    // uint8_t tmpBuf[300] = {0};
    // for (uint16_t index = 0; index < length; index++) {
    //     tmpBuf[index] = (*(data + index) & 0xff) << 3 | (*(data + index) & 0xff);
    // }
    // 数据发送
    Send(data, length);
}

void SendImageFinish(void) {
    // 帧尾发送
    uint8_t tail = 0x29;
    Send(&tail, 1);
}

void ProcessSerialSendImage(uint8_t* pData, uint16_t width, uint16_t height) {
    static uint8_t status;
    if (pData == NULL && status != STATUS_END) {
        return;
    }

    switch (status) {
    case STATUS_IDLE: {
        status = STATUS_START;
        SendImageStart(width, height);
    } break;
    case STATUS_START:
    case STATUS_SENDING: {
        status = STATUS_SENDING;
        SendImageData(pData, width);
    } break;
    case STATUS_END: {
        status = STATUS_IDLE;
        SendImageFinish();
    } break;
    default:
        break;
    }
}
